pipeline {
  agent any
  stages {
    stage('Prepare env') {
      steps {
        script {
          env.TIMESTRAP = sh(returnStdout: true, script: 'date +%Y%m%d%H%M%S').trim()
          env.DOCKER_TAG = "T-${env.TIMESTRAP}_GC-${env.GIT_COMMIT_SHORT}_BI-${env.CI_BUILD_ID}"
        }

        sh 'printenv'
      }
    }
    stage('Get Code') {
      steps {
        checkout([
          $class: 'GitSCM',
          branches: [[name: env.GIT_BUILD_REF]],
          userRemoteConfigs: [[
            url: env.GIT_REPO_URL,
            credentialsId: env.CREDENTIALS_ID
          ]]])
        }
      }
      stage('Install Pakcages') {
        agent {
          docker {
            // reuseNode true
            // registryUrl 'https://coding-public-docker.pkg.coding.net'
            // image 'public/docker/nodejs:14'
            image 'node:14.17.6-alpine3.13'
            reuseNode 'true'
          }

        }
        steps {
          sh 'node -v'
          sh 'npm -v'
          sh 'yarn -v'
          sh 'yarn install'
        }
      }
      stage('Prepare Static Tag'){
          agent {
          docker {
            reuseNode true
            registryUrl 'https://coding-public-docker.pkg.coding.net'
            image 'public/docker/nodejs:14'
          }

        }
        steps {
          dir('tools/scripts/constants/'){
              sh """
              :>static-tag.ts
              echo "const static_tag = '${env.DOCKER_TAG}';" > static-tag.ts
              echo "export { static_tag };" >> static-tag.ts
              cat static-tag.ts
              """

          }
        }
      }
      stage('Build') {
        agent {
          docker {
            // reuseNode 'true'
            // registryUrl 'https://coding-public-docker.pkg.coding.net'
            // image 'public/docker/nodejs:14'
            image 'node:14.17.6-alpine3.13'
            reuseNode 'true'
          }

        }
        steps {
          sh 'yarn release'
        }
      }
      stage('Commit Static Resource') {
        steps {
          sh 'git --version'
          dir('dist/git/') {
            sh 'ls'
            checkout([
              $class: 'GitSCM',
              branches: [[name: '*/main']],// if is gitee,it will be */master
              userRemoteConfigs: [[
                //url: 'https://gitee.com/SmileSB101/qing-qiu-react-static.git',
                url: 'https://github.com/WinterSmileSB101/qingqiu-site-static.git',
                //credentialsId: env.CREDENTIALS_ID
                credentialsId: env.GITHUB_CREDENTIALSID
              ]]])
            //   withCredentials([ usernamePassword(credentialsId: env.GITHUB_CREDENTIALSID,
            //   usernameVariable: "GIT_USERNAME",
            //   passwordVariable: "GIT_PASSWORD")
            //   //usernameVariable: "GITHUB_USERNAME",
            //   //passwordVariable: "GITHUB_PASSWORD")
            // ]) {
              //sh 'git config --local credential.helper "!p() { echo username=\\$GIT_USERNAME; echo password=\\$GIT_PASSWORD; }; p"'
              sh "git branch -a | egrep 'remotes/origin/${env.STATIC_GIT_BRANCH}' && (git checkout ${env.STATIC_GIT_BRANCH} && git pull) || (git branch '${env.STATIC_GIT_BRANCH}' && git push origin '${env.STATIC_GIT_BRANCH}')"
              // COPY refer: https://blog.csdn.net/weixin_39716800/article/details/116995914
              // COPY refer: https://blog.51cto.com/zhaoshilei/1790646
              sh '''
                ls
                cp ../publish/static . -vur
                '''

              sh """
              git add .
              git branch -a

              git config --global user.email 'zxb13194889618@outlook.com'
              git config --global user.name 'SmileSB101'

              git remote set-url origin  https://${env.GITHUB_TOKEN}@github.com/WinterSmileSB101/qingqiu-site-static.git

              git status | egrep 'nothing to commit, working tree clean' && echo 'not need commit this time.' || (git add . && git commit -m 'Add ${env.DOCKER_TAG} static changes,hash is ${env.GIT_COMMIT}' && git push origin HEAD:'${env.STATIC_GIT_BRANCH}')

              curl -X POST -H "Authorization: token ${env.GITHUB_TOKEN}" https://api.github.com/repos/WinterSmileSB101/qingqiu-site-static/releases -d '{"tag_name":"${env.DOCKER_TAG}","name":"static-release","body":"${env.DOCKER_TAG} static resource", "target_commitish":"${env.STATIC_GIT_BRANCH}"}'
              """
            // }

          }

        }
      }
    //   stage('Install Docker Packages') {
    //     agent {
    //       docker {
    //         reuseNode true
    //         registryUrl 'https://coding-public-docker.pkg.coding.net'
    //         image 'public/docker/nodejs:14'
    //       }
    //     }
    //     steps {
    //         dir('dist/publish/server/') {
    //             sh 'npm config get registry'
    //             sh 'npm install --production'
    //         }
    //     }
    //   }
      stage('Build Docker & Push Image') {
        steps {
          dir('dist/publish/server/') {
            echo 'New Tag is: ${env.DOCKER_TAG}'
            sh 'docker -v'
            sh "echo '${env.DOCKER_PWD}' | docker login '${env.DOCKER_REGISTRY}' -u='${env.DOCKER_USER_NAME}' --password-stdin"
            sh "docker build -t ${env.DOCKER_IMAGE_NAME}:${env.DOCKER_TAG} ."
            sh "docker push ${env.DOCKER_IMAGE_NAME}:${env.DOCKER_TAG}"

            //useCustomStepPlugin(key: 'coding-public:artifact_docker_push', version: '1.0', params: [properties:'[]',image:"${CODING_DOCKER_IMAGE_NAME}:${DOCKER_IMAGE_VERSION}",project:'qingqiu-site',username:'${PROJECT_TOKEN_GK}',password:'${PROJECT_TOKEN}',repo:'core'])
            useCustomStepPlugin(key: 'coding-public:artifact_docker_push', version: '1.0', params: [properties:'[]',image:"${DOCKER_IMAGE_NAME}:${DOCKER_TAG}",project:'qingqiu-site',username:'${PROJECT_TOKEN_GK}',password:'${PROJECT_TOKEN}',repo:'core'])
          }

        }
      }
    }
    environment {
      CODING_DOCKER_REG_HOST = "${CCI_CURRENT_TEAM}-docker.pkg.${CCI_CURRENT_DOMAIN}"
      CODING_DOCKER_IMAGE_NAME = "${PROJECT_NAME.toLowerCase()}/${DOCKER_REPO_NAME}/${DOCKER_IMAGE_NAME}"
    }
  }